import { sysLogin, sysProfile, sysUser } from '@/api/user'
import router, { asyncRoutes, constantRoutes } from '@/router'
export default {
  namespaced: true,
  state: {
    token: '',
    userInfo: ''
  },
  mutations: {
    setToken(state, value) {
      state.token = value
    },
    // 获取用户信息
    setUserInfo(state, value) {
      state.userInfo = value
    },
    // 删除token和用户信息
    deleteInformation(state) {
      state.token = ''
      state.userInfo = ''
    }
  },
  actions: {
    async toLogin(store, form) {
      // 调用登录页接口 如果成果执行下面代码 失败阻止下面代码
      const res = await sysLogin(form)
      // console.log(res)
      store.commit('setToken', res.data)
    },
    // 存储用户信息
    async getUserInfo(store) {
      const res = await sysProfile()
      const res2 = await sysUser(res.data.userId)
      const newArr = { ...res.data, ...res2.data }
      store.commit('setUserInfo', newArr)
      // 路由权限配置
      // console.log(asyncRoutes)
      // console.log(newArr)
      const routerArr = asyncRoutes.filter((item) => {
        return newArr.roles.menus.includes(item.meta.name)
      })
      // console.log(routerArr)
      // 调用路由方法添加路由
      routerArr.push({ path: '*', redirect: '/404', hidden: true })
      // 把获取的路由存储到vuex中
      store.commit('routes/setRouterList', [...routerArr, ...constantRoutes], {
        root: true
      })
      router.addRoutes(routerArr) // 要经过一次拦截器
    }
  },
  getters: {}
}
